﻿/*
 * This file is part of MonoStrategy.
 *
 * Copyright (C) 2010-2011 Christoph Husse
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: 
 *      # Christoph Husse
 * 
 * Also checkout our homepage: http://monostrategy.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace MonoStrategy
{
    public partial class Program
    {
        public static XMLGUIConfig GUIConfig { get; private set; }
        public static XMLGUILayout GUILayout { get; private set; }
        public static GUIBindings GUI { get; private set; }

        private static void UpdateGUIConfig()
        {
            var backupConfig = GUIConfig;
            var backupLayout = GUILayout;

            try
            {
                m_GUILoaderTimer.Change(Timeout.Infinite, Timeout.Infinite);

                lock (GUILoadLock)
                {
#if DEBUG
                    // in debug mode, the layout can be updated at runtime (resulting in some kind of GUI designer)
                    if (GUILayout != null)
                    {
                        if (new FileInfo(GetResourcePath("GUI/Default/Layout.xml")).LastWriteTime > GUILayout.LastWriteTime)
                            GUILayout = null;
                    }

                    if (GUIConfig != null)
                    {
                        if (new FileInfo(GetResourcePath("GUI/Default/Config.xml")).LastWriteTime > GUIConfig.LastWriteTime)
                        {
                            GUIConfig = null;
                            GUILayout = null;
                        }
                    }
#endif

                    if (GUIConfig == null)
                    {
                        GUIConfig = null;
                        GUIConfig = XMLGUIConfig.Load(Renderer, GetResourcePath("GUI/Default/Config.xml"));
                    }

                    if (GUILayout == null)
                    {
                        String fullPath = GetResourcePath("GUI/Default/Layout.xml");
                        String source = File.ReadAllText(fullPath);
                        
                        source = source.Replace("{Race}", Program.Map.Race.Name);

                        GUILayout = XMLGUILayout.Load(source, new FileInfo(fullPath));
                        BindGUI();
                    }
                    else
                    {
                        GUI.Update();
                    }
                }

                m_GUILoaderTimer.Change(1000, 1000);
            }
            catch (Exception e)
            {
                /*
                 * Restore previous layout and give the designer a chance to fix errors.
                 * When he closes the modal box, the design will try to update again...
                 */
                GUIConfig = backupConfig;
                GUILayout = backupLayout;

                Log.LogExceptionModal(e);

                m_GUILoaderTimer.Change(1000, 1000);
            }
        }

        private static void BindGUI()
        {
            ListBox[] buildingLists = new ListBox[]{
                (ListBox)GUILayout.RootElement.FindControl("#list:EconomyBuildings"),
                (ListBox)GUILayout.RootElement.FindControl("#list:FoodBuildings"),
                (ListBox)GUILayout.RootElement.FindControl("#list:WarBuildings"),
                (ListBox)GUILayout.RootElement.FindControl("#list:OtherBuildings")
            };

            if (buildingLists[0] == null)
                throw new ArgumentException("Config does not contain a list named \"#list:EconomyBuildings\".");
            if (buildingLists[1] == null)
                throw new ArgumentException("Config does not contain a list named \"#list:FoodBuildings\".");
            if (buildingLists[2] == null)
                throw new ArgumentException("Config does not contain a list named \"#list:WarBuildings\".");
            if (buildingLists[3] == null)
                throw new ArgumentException("Config does not contain a list named \"#list:OtherBuildings\".");

            foreach (var building in Program.Map.Race.Buildables)
            {
                buildingLists[building.TabIndex].AddItem(new ListBoxItem("Race/Romans/Buildings/" + building.AnimationClass + ".png")
                {
                    Callback = building,
                });
            }

            foreach (var list in buildingLists)
            {
                var current = list;

                current.OnSelectionChanged += (sender, oldItem, newItem) =>
                {
                    if (newItem != null)
                    {
                        ShowBuildingGrid((BuildingConfig)newItem.Callback);

                        foreach (var toUncheck in buildingLists)
                        {
                            if (toUncheck == current)
                                continue;

                            toUncheck.SelectionIndex = -1;
                        }
                    }
                };
            }

            GUI = new GUIBindings(GUILayout);
        }

        
    }
}
